import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'CFrom.dart';

class _IStore with ChangeNotifier {
  bool _autovalidate = false;
  get autovalidate => _autovalidate;
  void setAutovalidate() {
    _autovalidate = true;
    notifyListeners();
  }
}

class CInput extends StatelessWidget {
  final FormFieldValidator<String> validator;
  final InputDecoration decoration;
  final String name;

  CInput({
    this.validator,
    this.decoration,
    this.name,
  });
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (_) => _IStore(),
        ),
      ],
      child: _CInput(
        name: name,
        validator: validator,
        decoration: decoration,
      ),
    );
  }
}

class _CInput extends StatelessWidget {
  final FormFieldValidator<String> validator;
  final InputDecoration decoration;
  final String name;
  _CInput({
    this.validator,
    this.decoration,
    this.name,
  });

  @override
  Widget build(BuildContext context) {
    CFromStore fomstore = Provider.of<CFromStore>(context);
    _IStore store = Provider.of<_IStore>(context);
    return TextFormField(
      initialValue: fomstore.data[name],
      autovalidate: store.autovalidate,
      onChanged: (String value) {
        if (!store.autovalidate) {
          store.setAutovalidate();
        }
      },
      validator: (String value) {
        value = value.trim();
        if (validator != null) return validator(value);
        return null;
      },
      decoration: decoration,
      onSaved: (String value) {
        value = value.trim();
        fomstore.setData(name, value);
      },
    );
  }
}
